 //index.js
//获取应用实例
var app = getApp(); 
//倒计时函数
var interval = null; 
//HTTP请求request封装
var HttpRequest = require("../../http.js"); 
//CBC加密 
var CryptoJS = require("../../Crypto.js");
//RSA加密
var RSA = require("../../rsa.js"); 

Page({
  data: {
    userName: '',//电话号码
    userVer:'',//验证码
    date: '请选择日期',
    fun_id: 2, 
    time: '获取验证码', //倒计时 
    currentTime: 60,
    loadingHidden: true,//加载动画 
 
  },
  getReq: HttpRequest.getReq,//GET数据请求函数
  postReq: HttpRequest.postReq,//POST数据请求
  header: HttpRequest.header,//header参数
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    var that = this 
    const headers = {
      'Accept': 'application/json',
      "Content-Type": "application/x-www-form-urlencoded",
      "headMode": getApp().globalData.InitialHeadmode,
    }
    /**
     * 查询服务器端是否开启加密算法
     */
    //正式环境，在服务器启动时即设置，中途不允许修改，使用中修改则会导致操作异常，必须重新登录才行。要修改则只能保证没用户使用情况下，如凌晨。开发测试可正常修改
    const url = '/auth/needEncryption';
   
    HttpRequest.getReq(url, getApp().globalData.data, headers, function (res) { 
        if (res != true){
          wx.showToast({
            title: '此版本未开始信息安全加密，不建议登录使用！',
            icon: 'none',
            duration:3000
          })
        }else{
          const authUrl = "/auth/publicKey"
          HttpRequest.getReq(authUrl, getApp().globalData.data, headers, function (res) { 
            //随机私钥
            var PrivateKey = getApp().randomPassword(16);
            app.globalData.PrivateKey = PrivateKey;
            console.log("随机私钥:" + app.globalData.PrivateKey);
            //后台公钥加密
            var publicKey = '-----BEGIN PUBLIC KEY-----'+res+'-----END PUBLIC KEY-----';
            var input_rsa = PrivateKey;
            var encrypt_rsa = new RSA.RSAKey();
            encrypt_rsa = RSA.KEYUTIL.getKey(publicKey);
            var encStr = encrypt_rsa.encrypt(input_rsa)
            encStr = RSA.hex2b64(encStr); 
            app.globalData.PublicKey = encStr;
            console.log("已加密后台公钥：" + encStr);
            
          })
        }
      })
  },
  //获取手机号码
  userNameInput: function (e) { 
    //数据有效性验证
    var phone_number = e.detail.value;
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    if (phone_number.length == 0) {
      wx.showToast({
        title: '请输入手机号不能为空！',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    else if (phone_number.length != 11) {
      wx.showToast({
        title: '手机号长度有误！',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    else if (!myreg.test(phone_number)) {
      wx.showToast({
        title: '手机号格式错误！',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    else{
      this.setData({
        userName: e.detail.value
      })
    }
  }, 
  //获取验证码
  userVerification:function(e){
    this.setData({
      userVer: e.detail.value
    })
  },
  //验证码倒计时
  getCode: function (options) {
    var that = this;
    var currentTime = that.data.currentTime
    interval = setInterval(function () {
      currentTime--;
      that.setData({
        time: currentTime + '秒'
      })
      if (currentTime <= 0) {
        clearInterval(interval)
        that.setData({
          time: '重新发送',
          currentTime:61,
          disabled: false
        })
      }
    }, 1000)
  },
  //验证码发送 
  getVerificationCode() {
    var that = this
    //电话号码
    var phone_number = that.data.userName; 
    var headers = {
      'Accept': 'application/json',
      "Content-Type": "application/x-www-form-urlencoded",
      "headMode": getApp().globalData.InitialHeadmode,
    }
    if (phone_number != '') {
       //接口001.1.11发送验证码
      var url = '/user/v1/cmsCode/checkPhone?phone=' + phone_number + '&type=1 '
      HttpRequest.getReq(url, getApp().globalData.data,headers,function (res) {
        console.log(res);
        wx.showToast({
          title: res,
          icon: 'none',
          duration: 2000
        })
        that.getCode();
        that.setData({
          disabled: true
        })
      }) 
    }
  },
  //点击登录按钮
  loginBtnClick: function (e) {     

    var that = this 
    
    //验证码
    const phone_userVer = e.detail.value.Verification; 
    //电话号码 
    const phone_number = e.detail.value.phone
    if (phone_number.length == 0) {
      wx.showToast({
        title: '手机号码不能为空！',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    else if (phone_userVer.length == 0) {
      wx.showToast({
        title: '验证码不能为空！',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
     else if (phone_userVer.length != 6) {
      wx.showToast({
        title: '验证码必须为6位！',
        icon: 'none',
        duration: 2000
      })
      return false; 
    }
    else{

      /*
        **CBC加密
      */
      //登录公钥
      const PublicKey = app.globalData.PublicKey;
      console.log("已加密后台公钥：" + PublicKey);

      //随机私钥  
      const key = CryptoJS.enc.Utf8.parse(app.globalData.PrivateKey);
      console.log("随机私钥:" + key);

      //加密偏移量
      const options = {
        iv: CryptoJS.enc.Utf8.parse("bskyapp123456789"),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      };

      //CBC加密后的验证码
      const encryptedVerData = CryptoJS.AES.encrypt(phone_userVer, key, options);
      const encryptedVer = encryptedVerData.toString();
      console.log('CBC加密后的验证码：', encryptedVer);

      //CBC加密电话号码
      const encryptedPhoneData = CryptoJS.AES.encrypt(phone_number, key, options);
      const encryptedPhone = encryptedPhoneData.toString();
      console.log('CBC加密电话号码：', encryptedPhone);

      //全局变量储存电话号码
      app.globalData.phone = phone_number;
      //数据上传
      var JsonData = { 
        randomCek: PublicKey , //登录公钥
        phone: encryptedPhone, //电话号码
        cmsCode: encryptedVer, //用户验证码
        }
      //接口300.1.1登录请求
      var url = '/resident/v1/residentCmsLogin'
      //第一次登录HeadMode头部登录信息
      var headers = {
        'Accept': 'application/json',
        "Content-Type": "application/x-www-form-urlencoded",
        "headMode": getApp().globalData.InitialHeadmode,
      }

      //登录数据提交
      HttpRequest.postReq(url, JsonData, headers,function (res,code) { 
        const ResJson = res;
        console.log(res);
        wx.setStorage({ key: "login_Information", data: JSON.stringify(ResJson),})
        //登录成功后HeadMode头部登录信息
        var headArray = {
          "loginMark": res.loginMark, //登录标记
          "reqDigest": res.reqDigest,//返回值
          "category": "3", //微信统一进入传递参数为3
          "imei": "",
          "imsi": "",
          "phonetype": "",
          "timestamp": "1502951724089",
          "version": "2.0.1"//版本号
        } 
        //HeadMode登录信息储存
        wx.setStorage({ key: "UserLogin", data: JSON.stringify(headArray),});

        //登录信息判断识别 
        var isExist = res.isExist;
        var isChooseAD = res.isChooseAD;
        var token = res.token;
        //登录状态判别（判别是否已经进行了实名认证，而未申领健康卡）
        if (code == 200){
          if (isExist == true && isChooseAD == 2) {
            var InfoUrl = '/resident/healthcard/info?';
            app.globalData.LoginStatus = true;
            var headmode = {
              'Accept': 'application/json',
              "Content-Type": "application/x-www-form-urlencoded",
              "headMode": JSON.stringify(headArray),
              "token": token,
            }
            //判别是否已经拥有健康卡
            HttpRequest.getReq(InfoUrl, getApp().globalData.data , headmode, function (res, code) {

              if (code == 406) {
                wx.redirectTo({
                  url: '../apply/apply'
                })
              }
              else {
                wx.switchTab({
                  url: '../Health/Health'
                })
              }
            })
          }
          else {
            //未实名认证则进行实名认证
            wx.navigateTo({
              url: '../index/index'
            })
          }
        }
        else{
          wx.showToast({
            title: ResJson,
            icon: 'none',
            duration: 2000
          })
        }
       
        })  
    }
  },

})
